
package com.city.parking.util;

import java.lang.ref.WeakReference;


import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class Registrant {
    public Registrant(Handler h, int what, Object obj) {
        refH = new WeakReference<Handler>(h);
        this.what = what;
        userObj = obj;
    }

    public void clear() {
        refH = null;
        userObj = null;
    }

    public void notifyRegistrant() {
        internalNotifyRegistrant(null, null);
    }

    public void notifyResult(Object result) {
        internalNotifyRegistrant(result, null);
    }

    public void notifyException(Throwable exception) {
        internalNotifyRegistrant(null, exception);
    }

    /**
     * This makes a copy of @param ar
     */
    public void notifyRegistrant(AsyncResult ar) {
        internalNotifyRegistrant(ar.result, ar.exception);
    }

    /* package */void internalNotifyRegistrant(Object result, Throwable exception) {
        Handler h = getHandler();

        if (h == null) {
            clear();

            // / M: Registrant Debug Log Enhancement
            Log.d("Registrant",
                    "internalNotifyRegistrant(): Warning! Handler is null, it could be already GCed. ( what="
                            + what + ", userObj=" + userObj + ", result=" + result + ", exception="
                            + exception + " )");
        } else {
            Message msg = Message.obtain();

            msg.what = what;

            msg.obj = new AsyncResult(userObj, result, exception);

            h.sendMessage(msg);
        }
    }

    /**
     * NOTE: May return null if weak reference has been collected
     */

    public Message messageForRegistrant() {
        Handler h = getHandler();

        if (h == null) {
            clear();

            // / M: Registrant Debug Log Enhancement
            Log.d("Registrant",
                    "messageForRegistrant(): Warning! Handler is null, it could be already GCed. ( what="
                            + what + ", userObj=" + userObj + " )");
            return null;
        } else {
            Message msg = h.obtainMessage();

            msg.what = what;
            msg.obj = userObj;

            return msg;
        }
    }

    public Handler getHandler() {
        if (refH == null)
            return null;

        return (Handler) refH.get();
    }

    WeakReference<Handler> refH;
    int what;
    Object userObj;
}
